﻿// ***** Guidance generated code © Catharsis ***** //
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web.Mvc;

using Castle.DynamicProxy;
using $prjsn$.Common;
using $prjsn$.Entity;

using ProjectBase.Core;
using ProjectBase.Core.Tools.Import;

namespace $safeprojectname$
{
    [Serializable]
    public class CurrentProfileFilter : IInterceptor
    {
        public virtual void Intercept(IInvocation invocation)
        {
            if (!DoApplyFilter(invocation))
            {
                invocation.Proceed();
                return;
            }

            // pre
            var previous = BeforeExecuting(invocation);

            // BindEntity
            invocation.Proceed();

            // post
            AfterExecuted(invocation, previous);
        }

        protected virtual bool DoApplyFilter(IInvocation invocation)
        {
            // not of our interest
            if (invocation.Arguments.IsEmpty()) // first must be (entity) in place
            {
                return false;
            }

            // is it IAuditable?
            return invocation.Arguments[0] is IAuditable;
        }

        protected virtual IAuditable BeforeExecuting(IInvocation invocation)
        {
            var entity = invocation.Arguments[0] as IAuditable;
            return entity.Clone() as IAuditable;
        }

        protected virtual void AfterExecuted(IInvocation invocation, IAuditable previous)
        {
            var entity = invocation.Arguments[0] as IAuditable;

            // TODO
            // AuditChanges(entity, previous);
        }
    }
}